package com.paradise.phone.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;

import com.paradise.api.FaceCall;
import com.paradise.api.FacePhone;
import com.paradise.api.FacephoneListener;
import com.paradise.api.FacephonePreferences;
import com.paradise.phone.R;
import com.paradise.phone.fragment.VideoFragment;
import com.paradise.phone.utils.Numpad;
import com.paradise.phone.utils.ToastUtil;
import com.yanzhenjie.permission.AndPermission;

import org.linphone.core.CallDirection;
import org.linphone.core.LinphoneCall;
import org.linphone.core.LinphoneCallParams;
import org.linphone.core.LinphoneCallStats;
import org.linphone.core.LinphoneCore;
import org.linphone.core.LinphoneCoreException;
import org.linphone.core.Reason;

/**
 * Created by Sisyphus on 2017/9/5.
 */

public class TalkingAcitvity extends BaseActivity implements View.OnClickListener,
        FacephoneListener.FacephoneCallStateListener {

    private static final int PERMISSION_CAMERA = 0;
    private VideoFragment videoFragment;
    private String incommingType;

    private ImageView ivVideo;
    private ImageView ivAudio;
    private ImageView ivHangup;
    private TextView tvRemoteUser;
    private ImageView ivSpeaker;
    private ImageView ivNumpad;
    private ImageView ivPreviewEnable;

    private SurfaceView svRendingVideo;
    private SurfaceView svPreviewVideo;

    private ImageView ivAnimCalling;

    private LinphoneCore mLc;

    private RelativeLayout rlTopBanner;
    private TableLayout llBottomBanner;
    private boolean isHide = false;

    private TranslateAnimation taTopOut;
    private TranslateAnimation taBottomOut;
    private TranslateAnimation taTopIn;
    private TranslateAnimation taBottomIn;
    private ImageView ivInAudio;

    private FrameLayout flContainer;

    private ImageView ivSwitchCamera;
    private FrameLayout flPreviewVideo;

    private AlertDialog dialog;
    private boolean isSpeakerOn = true;

    private Chronometer chTalkingTime;
    private PopupWindow popupNumpad;
    private boolean isPreviewHide = false;
    private LinphoneCall currentCall;
    private AudioManager audioManager;

    private boolean isVideoEnable = true;
    private boolean isNumpadHide = true;
    private boolean isMicEnable = false;
    private LinphoneCallStats stats;
    private float downX = -1;
    private float upX = -1;
    private View view;
    private Dialog argumentDialog;

    TextView tvCodec;
    TextView tvEncoder;
    TextView tvDecoder;
    TextView tvUploadBandwidth;
    TextView tvDownloadBandwidth;
    TextView tvICEConnectivity;
    TextView tvIPFamily;
    TextView tvSenderLossRate;
    TextView tvReceiverLossRate;
    TextView tvJitterBuffer;
    TextView tvCodecV;
    TextView tvEncoderV;
    TextView tvDecoderV;
    TextView tvUploadBandwidthV;
    TextView tvDownloadBandwidthV;
    TextView tvICEConnectivityV;
    TextView tvIPFamilyV;
    TextView tvSenderLossRateV;
    TextView tvReceiverLossRateV;
    TextView tvSentVideoResolution;
    TextView tvReveivedVideoResolution;
    private LinphoneCallStats audioStates;
    private Thread argumentThread;
    private LinphoneCallStats videoStates;
    private LinphoneCallParams lpArgument;
    private boolean mPlayDtmf = true;
    private boolean mIsDtmfStarted = false;
    private boolean isCameraOpened = true;
    private AlertDialog requestDialog = null;

    private LinearLayout progressBar;

    private boolean isConverting = false;

    private boolean isCallError = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_talking);

        if (getIntent().getStringExtra("INCOMMING_CALL_TYPE") != null) {
            incommingType = getIntent().getStringExtra("INCOMMING_CALL_TYPE");
        } else {
            return;
        }

        mLc = FacePhone.instance().getmLc();

        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        switch2player(true);

        initView(savedInstanceState);
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        FacePhone.instance().addCallStateListener(this);
    }

    private void initView(Bundle savedInstanceState) {

        taTopOut = (TranslateAnimation) AnimationUtils
                .loadAnimation(this, R.anim.anim_top_out);
        taBottomOut = (TranslateAnimation) AnimationUtils
                .loadAnimation(this, R.anim.anim_bottom_out);
        taTopIn = (TranslateAnimation) AnimationUtils
                .loadAnimation(this, R.anim.anim_top_in);
        taBottomIn = (TranslateAnimation) AnimationUtils
                .loadAnimation(this, R.anim.anim_bottom_in);

        ivAudio = findViewById(R.id.iv_mic_muted);
        ivVideo = findViewById(R.id.iv_video_enable);
        ivHangup = findViewById(R.id.iv_hang_up);
        ivAnimCalling = findViewById(R.id.iv_anim_calling);
        ivNumpad = findViewById(R.id.iv_numpad);
        ivSpeaker = findViewById(R.id.iv_speaker);
        ivPreviewEnable = findViewById(R.id.iv_preview_enable);
        tvRemoteUser = findViewById(R.id.tv_remote_user);
        rlTopBanner = findViewById(R.id.rl_top);
        llBottomBanner = findViewById(R.id.ll_bottom);
        flContainer = findViewById(R.id.fl_video_container);
        chTalkingTime = findViewById(R.id.chro_talk_time);
        progressBar = findViewById(R.id.video_in_progress);

        if (mLc.getCurrentCall() != null)
            if (mLc.getCurrentCall().getDirection().equals(CallDirection.Incoming)) {
                dynamicAddFragment();
                chTalkingTime.setBase(SystemClock.elapsedRealtime());
                chTalkingTime.start();
            }

        if (savedInstanceState != null) {
            //restoreState(savedInstanceState);
        }

        if (mLc.getCurrentCall() == null)
            return;

        if (mLc.getCurrentCall().getDirection().equals(CallDirection.Outgoing)) {
            ivAnimCalling.setVisibility(View.VISIBLE);
            AnimationDrawable animationDrawable = (AnimationDrawable) ivAnimCalling.getDrawable();
            animationDrawable.start();
        } else {
            ivAnimCalling.setVisibility(View.INVISIBLE);
        }

        tvRemoteUser.setText("与" + mLc.getCurrentCall().getRemoteAddress().getUserName() + "通话中");
    }

    private void initEvent() {
        ivAudio.setOnClickListener(this);
        ivHangup.setOnClickListener(this);
        ivVideo.setOnClickListener(this);
        ivNumpad.setOnClickListener(this);
        ivSpeaker.setOnClickListener(this);
        ivPreviewEnable.setOnClickListener(this);

        hideBanner();
    }

    private void dynamicAddFragment() {
        Bundle bundle = new Bundle();
        bundle.putString("INCOMMING_CALL_TYPE", incommingType);

        if (videoFragment == null) {
            videoFragment = new VideoFragment();
        }
        videoFragment.setArguments(bundle);

        getFragmentManager().beginTransaction()
                .replace(R.id.fl_video_container, videoFragment)
                .commit();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_hang_up:
                FaceCall.instance().terminateCurrentCall();
                finish();
                break;

            case R.id.iv_mic_muted:
                FaceCall.instance().micMuted();
                if (FaceCall.instance().isMuted()) {
                    ivAudio.setImageResource(R.mipmap.mic_disable);
                } else {
                    ivAudio.setImageResource(R.mipmap.mic_enable);
                }
                isMicEnable = FaceCall.instance().isMuted();
                break;

            case R.id.iv_video_enable:

                if (videoFragment == null)
                    return;
                if ((svRendingVideo = videoFragment.getSvRendingVideo()) != null
                        && (svPreviewVideo = videoFragment.getSvPreviewVideo()) != null) {
                    progressBar.setVisibility(View.VISIBLE);
                    isConverting = true;
                    FaceCall.instance().disableVideo(isVideoEnabled(mLc.getCurrentCall()));
                }

                break;

            case R.id.iv_speaker:
                switch2player(!isSpeakerOn);
                //mLc.enableSpeaker(!isSpeakerOn);
                isSpeakerOn = !isSpeakerOn;
                if (isSpeakerOn) {
                    ivSpeaker.setImageResource(R.mipmap.speaker_on);
                } else {
                    ivSpeaker.setImageResource(R.mipmap.speaker_off);
                }
                break;

            case R.id.iv_numpad:
                if (popupNumpad == null) {
                    View viewNumpad = LayoutInflater.from(this).inflate(R.layout.popup_numpad, null);
                    final EditText editNum = (EditText) viewNumpad.findViewById(R.id.et_popup_num);
                    Numpad numpad = (Numpad) viewNumpad.findViewById(R.id.numpad_popup);
                    numpad.setOnDigitClickListener(new Numpad.OnDigitClickListener() {
                        @Override
                        public void onDigitClickListener(View view, String s) {
                            editNum.append(s);
                            if(mPlayDtmf) {
                                LinphoneCore lc = FacePhone.instance().getmLc();
                                lc.stopDtmf();
                                mIsDtmfStarted = false;
                                if (lc.isIncall()) {
                                    lc.sendDtmf(s.subSequence(0, 1).charAt(0));
                                    //Log.d("flag->", "TalkingAcitvity.java(onDigitClickListener:320)->sendDtmf");
                                }
                            }
                        }

                        @Override
                        public void onDigitTouchListener(View digit, String num, MotionEvent event) {
                            if (!mPlayDtmf) return;

                            LinphoneCore lc = FacePhone.instance().getmLc();
                            if (event.getAction() == MotionEvent.ACTION_DOWN && !mIsDtmfStarted) {
                                lc.playDtmf(num.subSequence(0, 1).charAt(0), -1);
                                mIsDtmfStarted = true;
                                //Log.d("flag->", "TalkingAcitvity.java(onDigitTouchListener:333)->playDtmf");
                            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                                lc.stopDtmf();
                                mIsDtmfStarted = false;
                                //Log.d("flag->", "TalkingAcitvity.java(onDigitTouchListener:337)->stopDtmf");
                            }
                        }
                    });
                    popupNumpad = new PopupWindow(viewNumpad, dip2px(250), dip2px(250));
                    popupNumpad.showAtLocation(flContainer, Gravity.CENTER, 0, 0);
                } else if (popupNumpad.isShowing()) {
                    popupNumpad.dismiss();
                    isNumpadHide = true;
                } else {
                    popupNumpad.showAtLocation(flContainer, Gravity.CENTER, 0, 0);
                    isNumpadHide = false;
                }
                break;

            case com.paradise.phone.R.id.iv_preview_enable:
                if (svRendingVideo.getVisibility() == View.INVISIBLE)
                    return;
                if (!isPreviewHide) {
                    svPreviewVideo.setVisibility(View.INVISIBLE);
                    ivSwitchCamera.setVisibility(View.INVISIBLE);
                    ivPreviewEnable.setImageResource(R.mipmap.preview_disable);
                } else {
                    svPreviewVideo.setVisibility(View.VISIBLE);
                    ivSwitchCamera.setVisibility(View.VISIBLE);
                    ivPreviewEnable.setImageResource(R.mipmap.preview_enable);
                }
                isPreviewHide = !isPreviewHide;
                break;
        }

    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        ivAnimCalling.setVisibility(View.INVISIBLE);
    }

    public void callbackFragment(SurfaceView svPreviewVideo, SurfaceView svRendingVideo,
                                 ImageView ivInAudio, ImageView ivSwitchCamera, FrameLayout flPreviewVideo) {
        this.svPreviewVideo = svPreviewVideo;
        this.svRendingVideo = svRendingVideo;
        this.ivInAudio = ivInAudio;
        this.ivSwitchCamera = ivSwitchCamera;
        this.flPreviewVideo = flPreviewVideo;
    }

    @Override
    public void callState(LinphoneCore linphoneCore, final LinphoneCall linphoneCall, final LinphoneCall.State state,
                          String s, boolean isAutoAnswer, boolean isVideoCall) {

        Log.d("flag->", "TalkingAcitvity.java(callState:373)->" + s);

        if (currentCall == null) {
            currentCall = linphoneCall;
        }

        if (state.equals(LinphoneCall.State.Connected)) {
            ivAnimCalling.setVisibility(View.INVISIBLE);
            dynamicAddFragment();
            chTalkingTime.setBase(SystemClock.elapsedRealtime());
            chTalkingTime.start();

            hideBanner();

            if (linphoneCall.getRemoteParams() != null
                    && !linphoneCall.getRemoteParams().getVideoEnabled()) {
                if (svRendingVideo != null)
                    svRendingVideo.setVisibility(View.INVISIBLE);
                ivVideo.setImageResource(com.paradise.phone.R.mipmap.video_disable);
            }
        }

        if (state.equals(LinphoneCall.State.StreamsRunning)) {
            stats = linphoneCall.getVideoStats();
            if (isConverting) {
                progressBar.setVisibility(View.GONE);
                switchVideo(isVideoEnabled(linphoneCall));
                isConverting = false;
            }
        }

        if (state.equals(LinphoneCall.State.Error)) {
            Reason reason = linphoneCall.getErrorInfo().getReason();
            String errorInfo = null;
            if (reason.equals(Reason.Declined)) {
                errorInfo = "对方拒接";
            } else if (reason.equals(Reason.Busy)) {
                errorInfo = "用户忙";
            } else if (reason.equals(Reason.TemporarilyUnavailable)) {
                errorInfo = "没有该用户，请检查号码";
            } else if (reason.equals(Reason.NotAnswered)) {
                errorInfo = "用户长时间没有回应";
            } else if (reason.equals(Reason.ServerTimeout)) {
                errorInfo = "服务器超时";
            } else if (reason.equals(Reason.Unauthorized)) {
                errorInfo = "未经授权";
            } else if (reason.equals(Reason.NotFound)) {
                errorInfo = "没有找到";
            } else {
                errorInfo = reason.toString();
            }

            if (errorInfo != null) {
                ToastUtil.showToast(this, errorInfo);
                Intent intent = new Intent(this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
                currentCall = null;
                return;
            }
        }

        if (state.equals(LinphoneCall.State.CallEnd) || state.equals(LinphoneCall.State.CallReleased)) { // 通话结束并释放
            if (currentCall.getRemoteAddress().getUserName()
                    .equals(linphoneCall.getRemoteAddress().getUserName())) {

                ToastUtil.showToast(this, "通话结束");
                Intent intent = new Intent(this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
                finish();
                currentCall = null;
            }
        }

        if (state.equals(LinphoneCall.State.CallUpdatedByRemote)) { // 远程通话参数更新

            boolean videoEnabled = FacephonePreferences.instance().isVideoEnabled();
            if (!videoEnabled) {
                acceptCallUpdate(false);
            }

            boolean remoteVideo = linphoneCall.getRemoteParams().getVideoEnabled();
            boolean localVideo = linphoneCall.getCurrentParams().getVideoEnabled();
            boolean autoAcceptCameraPolicy = FacephonePreferences.instance().shouldAutomaticallyAcceptVideoRequests();
            if (remoteVideo && !localVideo && !autoAcceptCameraPolicy && !mLc.isInConference()) {
                showAcceptCallUpdateDialog();
            }
        }

        if (state.equals(LinphoneCall.State.CallUpdating)){
            //ToastUtil.showToast(this, "通话更新中");
        }

        if (state == LinphoneCall.State.Paused
                || state == LinphoneCall.State.PausedByRemote
                || state == LinphoneCall.State.Pausing){
            //ToastUtil.showToast(this, "通话暂停");
        }

    }

    /**
     * 是否接受通话参数更新
     * @param accept
     */
    public void acceptCallUpdate(boolean accept) {

        LinphoneCall call = mLc.getCurrentCall();
        if (call == null) {
            return;
        }

        LinphoneCallParams params = mLc.createCallParams(call);
        if (accept) {
            params.setVideoEnabled(true);
            mLc.enableVideo(true, true);
        }

        try {
            mLc.acceptCallUpdate(call, params);
        } catch (LinphoneCoreException e) {
            Log.d("flag->", "TalkingAcitvity.java(acceptCallUpdate:583)->"+e);
        }
    }

    /**
     * 显示询问用户是否接受音视频切换的对话框
     */
    private void showAcceptCallUpdateDialog() {
        if (requestDialog == null)
        requestDialog = new AlertDialog.Builder(this)
                .setMessage("对方请求从音频切换到视频，是否同意？")
                .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
                        Log.d("flag->","[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));

                        if (camera == PackageManager.PERMISSION_GRANTED) {
                            acceptCallUpdate(true);
                        } else {
                            AndPermission.with(TalkingAcitvity.this)
                                    .requestCode(PERMISSION_CAMERA)
                                    .permission(Manifest.permission.CAMERA)
                                    .start();
                        }
                        requestDialog.dismiss();
                        requestDialog = null;
                    }
                })
                .setNegativeButton("不同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        acceptCallUpdate(false);
                        requestDialog.dismiss();
                        requestDialog = null;
                    }
                })
                .create();

        if (!requestDialog.isShowing()) {
            requestDialog.show();
        }
    }

    private boolean isVideoEnabled(LinphoneCall call) {
        if(call != null){
            return call.getCurrentParams().getVideoEnabled();
        }
        return false;
    }

    /**
     * 更新音视频通话界面UI
     * @param isVideoEnable
     */
    private void switchVideo(boolean isVideoEnable){

        if (isVideoEnable) {
            ivVideo.setImageResource(R.mipmap.video_enable);
            svPreviewVideo.setVisibility(View.VISIBLE);
            svRendingVideo.setVisibility(View.VISIBLE);
            ivSwitchCamera.setVisibility(View.VISIBLE);
            ivInAudio.setVisibility(View.INVISIBLE);

            this.isVideoEnable = true;

            hideBanner();

        } else {
            ivVideo.setImageResource(R.mipmap.video_disable);
            svPreviewVideo.setVisibility(View.INVISIBLE);
            svRendingVideo.setVisibility(View.INVISIBLE);
            ivSwitchCamera.setVisibility(View.INVISIBLE);
            ivInAudio.setVisibility(View.VISIBLE);

            this.isVideoEnable = false;

            showBanner();
        }
    }

    public void hideBanner() {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isHide) {
                    if (svRendingVideo != null) {
                        if (svRendingVideo.getVisibility() == View.VISIBLE) {
                            taTopOut.setFillAfter(true);
                            rlTopBanner.startAnimation(taTopOut);
                            taBottomOut.setFillAfter(true);
                            llBottomBanner.startAnimation(taBottomOut);
                            if (flPreviewVideo != null) {
                                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) flPreviewVideo.getLayoutParams();
                                lp.topMargin = dip2px(8);
                                flPreviewVideo.setLayoutParams(lp);
                            }
                            isHide = true;
                        }
                    }
                }
            }
        }, 5000);
    }

    public void showBanner() {
        isHide = false;
        taTopIn.setFillAfter(true);
        rlTopBanner.startAnimation(taTopIn);
        taBottomIn.setFillAfter(true);
        llBottomBanner.startAnimation(taBottomIn);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) flPreviewVideo.getLayoutParams();
        lp.topMargin = dip2px(50);
        flPreviewVideo.setLayoutParams(lp);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                View view = LayoutInflater.from(this).inflate(R.layout.ask_is_hang_up, null);
                TextView tvNo = (TextView) view.findViewById(R.id.tv_ask_no);
                TextView tvYes = (TextView) view.findViewById(R.id.tv_ask_yes);
                tvNo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                tvYes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        FaceCall.instance().terminateCurrentCall();
                    }
                });

                if (dialog == null) {
                    dialog = new AlertDialog.Builder(this, R.style.IncommingCallDialog)
                            .setView(view)
                            .create();
                }

                if (!dialog.isShowing()) {
                    dialog.show();
                }

                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    private int dip2px(float dpValue) {

        float scale = getResources().getDisplayMetrics().density;

        return (int) (dpValue * scale + 0.5f);
    }

    private void switch2player(boolean on) {
        if (on) {
            audioManager.setSpeakerphoneOn(true);
            audioManager.setMode(AudioManager.MODE_NORMAL);
            //设置音量，解决有些机型切换后没声音或者声音突然变大的问题
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                    audioManager.getStreamVolume(AudioManager.STREAM_MUSIC), AudioManager.FX_KEY_CLICK);
        } else {
            audioManager.setSpeakerphoneOn(false);

            //5.0以上
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
                //设置音量，解决有些机型切换后没声音或者声音突然变大的问题
                audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                        audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), AudioManager.FX_KEY_CLICK);

            } else {
                audioManager.setMode(AudioManager.MODE_IN_CALL);
                audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                        audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), AudioManager.FX_KEY_CLICK);
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("isSpeakerOn", isSpeakerOn);
        outState.putBoolean("isPreviewHide", isPreviewHide);
        outState.putBoolean("isMicEnable", isMicEnable);
        outState.putBoolean("isNumpadHide", isNumpadHide);
        outState.putBoolean("isVideoEnable", isVideoEnable);
        outState.putString("time", chTalkingTime.getText().toString());
        Log.e("test", "时间" + chTalkingTime.getText().toString());
    }

    private void restoreState(Bundle bundle) {
        isSpeakerOn = bundle.getBoolean("isSpeakerOn");
        isPreviewHide = bundle.getBoolean("isPreviewHide");
        isMicEnable = bundle.getBoolean("isMicEnable");
        isNumpadHide = bundle.getBoolean("isNumpadHide");
        isVideoEnable = bundle.getBoolean("isVideoEnable");
        chTalkingTime.stop();
        //chTalkingTime.setBase(SystemClock.elapsedRealtime()-Integer.parseInt(bundle.getString("time"))*1000);
        chTalkingTime.setText(bundle.getString("time"));
        chTalkingTime.start();

        if (isSpeakerOn) {
            ivSpeaker.setImageResource(R.mipmap.speaker_on);
            switch2player(true);
        } else {
            ivSpeaker.setImageResource(R.mipmap.speaker_off);
            switch2player(false);
        }

        if (isPreviewHide) {
            ivPreviewEnable.setImageResource(R.mipmap.preview_disable);
            if (flPreviewVideo != null) flPreviewVideo.setVisibility(View.INVISIBLE);
        } else {
            ivPreviewEnable.setImageResource(R.mipmap.preview_enable);
            if (flPreviewVideo != null) flPreviewVideo.setVisibility(View.VISIBLE);
        }

        if (isMicEnable) {
            ivAudio.setImageResource(R.mipmap.mic_disable);
        } else {
            ivAudio.setImageResource(R.mipmap.mic_enable);
        }

        if (isVideoEnable) {
            ivVideo.setImageResource(R.mipmap.video_enable);
        } else {
            ivVideo.setImageResource(R.mipmap.video_disable);
        }
        if (mLc != null && currentCall != null) {
            LinphoneCallParams callParams = currentCall.getCurrentParamsCopy();
            if (isVideoEnable) {
                callParams.setVideoEnabled(true);
            } else {
                callParams.setVideoEnabled(false);
            }

            mLc.updateCall(mLc.getCurrentCall(), callParams);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (argumentDialog != null) {
            argumentDialog.dismiss();
        }
        if (popupNumpad != null){
            popupNumpad.dismiss();
        }
        if (dialog != null){
            dialog.dismiss();
        }
        if (requestDialog != null){
            requestDialog.dismiss();
        }
        getFragmentManager().beginTransaction().remove(new Fragment());
    }

    public void showBannerByFragment() {
        if (isHide) {
            isHide = false;
            taTopIn.setFillAfter(true);
            rlTopBanner.startAnimation(taTopIn);
            taBottomIn.setFillAfter(true);
            llBottomBanner.startAnimation(taBottomIn);
            if (flPreviewVideo != null) {
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) flPreviewVideo.getLayoutParams();
                lp.topMargin = dip2px(50);
                flPreviewVideo.setLayoutParams(lp);
            }
            hideBanner();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {

            case MotionEvent.ACTION_DOWN:
                if (ev.getX() < 30) {
                    downX = 0;
                }
                break;
            case MotionEvent.ACTION_UP:
                if (downX != 0) {
                    break;
                }
                upX = ev.getX();
                if (upX - downX > 150) {
                    showTalkingArgument();
                    downX = -1;
                }
                break;

        }

        return super.dispatchTouchEvent(ev);
    }

    private void showTalkingArgument() {
        if (argumentDialog == null) {
            argumentDialog = new Dialog(this, R.style.Theme_Light_Dialog);

            view = LayoutInflater.from(TalkingAcitvity.this)
                    .inflate(R.layout.layout_talking_argument, null);

            tvCodec = (TextView) view.findViewById(R.id.tv_codec);
            tvEncoder = (TextView) view.findViewById(R.id.tv_encoder);
            tvDecoder = (TextView) view.findViewById(R.id.tv_decoder);
            tvUploadBandwidth = (TextView) view.findViewById(R.id.tv_upload_bandwidth);
            tvDownloadBandwidth = (TextView) view.findViewById(R.id.tv_download_bandwidth);
            tvICEConnectivity = (TextView) view.findViewById(R.id.tv_ice_connectivity);
            tvIPFamily = (TextView) view.findViewById(R.id.tv_ip_family);
            tvSenderLossRate = (TextView) view.findViewById(R.id.tv_sender_loss_rate);
            tvReceiverLossRate = (TextView) view.findViewById(R.id.tv_receiver_loss_rate);
            tvJitterBuffer = (TextView) view.findViewById(R.id.tv_jitter_buffer);
            tvCodecV = (TextView) view.findViewById(R.id.tv_v_codec);
            tvEncoderV = (TextView) view.findViewById(R.id.tv_v_encoder);
            tvDecoderV = (TextView) view.findViewById(R.id.tv_v_decoder);
            tvUploadBandwidthV = (TextView) view.findViewById(R.id.tv_v_upload_bandwidth);
            tvDownloadBandwidthV = (TextView) view.findViewById(R.id.tv_v_download_bandwidth);
            tvICEConnectivityV = (TextView) view.findViewById(R.id.tv_v_ice_connectivity);
            tvIPFamilyV = (TextView) view.findViewById(R.id.tv_v_ip_family);
            tvSenderLossRateV = (TextView) view.findViewById(R.id.tv_v_sender_loss_rate);
            tvReceiverLossRateV = (TextView) view.findViewById(R.id.tv_v_receiver_loss_rate);
            tvSentVideoResolution = (TextView) view.findViewById(R.id.tv_sent_video_resolution);
            tvReveivedVideoResolution = (TextView) view.findViewById(R.id.tv_reveived_video_resolution);

            //获得dialog的window窗口
            Window window = argumentDialog.getWindow();
            //设置dialog在屏幕底部
            window.setGravity(Gravity.LEFT);
            //设置dialog弹出时的动画效果，从屏幕底部向上弹出
            window.setWindowAnimations(R.style.argumentdialog);
            window.getDecorView().setPadding(0, 0, 0, 0);
            //获得window窗口的属性
            android.view.WindowManager.LayoutParams lp = window.getAttributes();
            //设置窗口宽度为充满全屏
            lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
            //设置窗口高度为包裹内容
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;
            //将设置好的属性set回去
            window.setAttributes(lp);
            argumentDialog.setContentView(view);
        }

        if (!argumentDialog.isShowing()) {
            argumentDialog.show();
        }

        setArgument();
    }

    private void setArgument() {
        if (currentCall != null) {
            lpArgument = currentCall.getCurrentParamsCopy();
            try {
                String audioMime = lpArgument.getUsedAudioCodec().getMime();
                String videoMime = lpArgument.getUsedVideoCodec().getMime();

                tvCodec.setText(audioMime + " / "
                        + (lpArgument.getUsedAudioCodec().getRate() / 1000) + "kHz");
                tvEncoder.setText(mLc.getMSFactory().getEncoderText(audioMime));
                tvDecoder.setText(mLc.getMSFactory().getDecoderText(audioMime));

                tvCodecV.setText(videoMime + " / "
                        + (lpArgument.getUsedVideoCodec().getRate() / 1000) + "kHz");
                tvEncoderV.setText(mLc.getMSFactory().getEncoderText(videoMime));
                tvDecoderV.setText(mLc.getMSFactory().getDecoderText(videoMime));
            } catch (NullPointerException e) {
            }

            if (argumentThread == null) {
                argumentThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (argumentDialog.isShowing()) {
                            updateArgvHandler.sendEmptyMessage(0);
                            SystemClock.sleep(1500);
                        }
                    }
                });
            }
            try {
                argumentThread.start();
            } catch (IllegalThreadStateException e) {
            }
        }
    }

    private Handler updateArgvHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:

                    if (currentCall != null) audioStates = currentCall.getAudioStats();
                    else break;
                    if (currentCall != null) videoStates = currentCall.getVideoStats();
                    else break;
                    tvUploadBandwidth.setText((int)audioStates.getUploadBandwidth() + "kbits/s");
                    tvDownloadBandwidth.setText((int)audioStates.getDownloadBandwidth() + "kbits/s");
                    tvICEConnectivity.setText(audioStates.getIceState().toString());
                    tvSenderLossRate.setText((int)audioStates.getSenderLossRate() + "%");
                    tvReceiverLossRate.setText((int)audioStates.getReceiverLossRate() + "%");
                    tvJitterBuffer.setText((int)audioStates.getJitterBufferSize() + "ms");

                    tvUploadBandwidthV.setText((int)videoStates.getUploadBandwidth() + "kbits/s");
                    tvDownloadBandwidthV.setText((int)videoStates.getDownloadBandwidth() + "kbits/s");
                    tvICEConnectivityV.setText(videoStates.getIceState().toString());
                    tvSenderLossRateV.setText((int)videoStates.getSenderLossRate() + "%");
                    tvReceiverLossRateV.setText((int)videoStates.getReceiverLossRate() + "%");
                    tvSentVideoResolution.setText(lpArgument.getSentVideoSize().height + "x"
                            + lpArgument.getSentVideoSize().width);
                    tvReveivedVideoResolution.setText(lpArgument.getReceivedVideoSize().height + "x"
                            + lpArgument.getReceivedVideoSize().width);
                    break;
            }
        }
    };

}
